package keepy.tech.maven.assistant;

import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.function.Consumer;

@Slf4j
public class DependencyExistenceChecker {

    private final OkHttpClient client;

    private final RepositoryLoader repoLoader;

    private final DependencyLoader deptLoader;

    public DependencyExistenceChecker(RepositoryLoader repoLoader, DependencyLoader dependencyLoader) {
        this.client = new OkHttpClient();
        this.repoLoader = repoLoader;
        this.deptLoader = dependencyLoader;
    }

    public static void main(String[] args) throws IOException {
        new DependencyExistenceChecker(
                new ClasspathRepositoryLoader(),
                new ClasspathDependencyLoader()
        ).checkExistence();
    }

    public void checkExistence() throws IOException {
        for (Repository repo : repoLoader.loadRepositories()) {
            for (Dependency dept : deptLoader.loadDependencies()) {
                callHttpRequest(repo, dept, response -> {
                    if (log.isDebugEnabled()) {
                        log.debug("Response is {}", response);
                    }
                    if (response.isSuccessful()) {
                        log.info("\u001B[32m{} exists in {}\u001B[0m", dept.urlJarPresentation(), repo.getUrl());
                    } else {
                        log.info("\u001B[31m{} NOT exist in {}\u001B[0m", dept.urlJarPresentation(), repo.getUrl());
                    }
                });
            }
        }
    }

    private void callHttpRequest(Repository repository, Dependency dependency, Consumer<Response> cb) throws IOException {
        String url = repository.getUrl().toString();
        if (url.charAt(url.length() - 1) != '/') {
            url += '/';
        }

        Request request = new Request.Builder()
                .url(url + dependency.urlJarPresentation())
                .head()
                .build();

        if (log.isDebugEnabled()) {
            log.debug("Checking {} existence ...", request.url());
        }
        try (Response response = client.newCall(request).execute()) {
            cb.accept(response);
        }
    }
}
